package com.ricchieri.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.dao.interf.ICharterDao;
import com.ricchieri.filter.CharterFilter;
import com.ricchieri.model.Charter;
import com.ricchieri.util.StringUtils;

public class CharterDao extends GenericDao implements ICharterDao {
	private static final long serialVersionUID = 3423459329621006995L;

	@Override
	@SuppressWarnings("unchecked")
	public List<Charter> getAllCharter(CharterFilter charterFilter) {
		Criteria criteria = criteriaAllCharters(charterFilter);
		
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Charter> getAllCharterPaginatedByFilter(
			CharterFilter charterFilter, int startRecord) {
		Criteria criteria = criteriaAllCharters(charterFilter);
		criteria.setMaxResults(BusinessSettings.ROW_MAX_RESULT);
		criteria.setFirstResult(startRecord);
		
		return criteria.list();
	}

	@Override
	public int getAllCharterCountByFilter(CharterFilter charterFilter) {
		Criteria criteria = criteriaAllCharters(charterFilter);
		Long result = (Long)criteria.setProjection(Projections.rowCount()).uniqueResult();
		return new Integer(result.intValue());
	}
	
	@Override
	public Charter getCharterById(CharterFilter charterFilter) {
		Criteria criteria = criteriaAllCharters(charterFilter);
		
		return (Charter) criteria.list().get(0);
	}
		
	private Criteria criteriaAllCharters(CharterFilter charter) {
		Criteria criteria = super.criteriaAllBasic(charter, Charter.class);
		
		if (!StringUtils.isEmpty(charter.getPatent())) {
			criteria.add(Restrictions.like(getTableName().concat(".patent"), "%".concat(charter.getPatent()).concat("%")));
		}
		
		if (charter.getCharterNumber() >0) {
			criteria.add(Restrictions.eq(getTableName().concat(".charterNumber"), charter.getCharterNumber()));
		}
		
		if (!StringUtils.isEmpty(charter.getCharterType())) {
			criteria.createAlias(getTableName().concat(".charterType"), "charterType");
			criteria.add(Restrictions.eq("charterType.id", charter.getCharterTypeId()));
		}
		
		return criteria;
	}

	@Override
	protected String getTableName() {
		return "charter";
	}
}
